from openai import OpenAI
from typing import List, Tuple
import time

def ask_questions(file_path: str, client: OpenAI, model: str = "Qwen3-8B") -> List[Tuple[str, str]]:
    results = []
    idx = 0 
    context_str = ""  # 用于保存上下文的字符串 
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line_number, line in enumerate(file, start=1):
                line = line.strip()
                if not line:
                    continue

                try:
                    system, user = line.split('|', 1)
                except ValueError:
                    print(f"跳过第 {line_number} 行：格式不正确（缺少 '|' 分隔符）")
                    continue

                # 构造完整的 prompt，包含上下文
                full_prompt = f"以下是之前的对话历史：\n{context_str}\n\n当前问题：{user.strip()}"
                messages = [
                    {"role": "system", "content": system.strip()},
                    {"role": "user", "content": full_prompt}
                ]

                try:
                    start_time = time.time() 
                    response = client.chat.completions.create(
                        model=model,
                        messages=messages
                    )
                    answer = response.choices[0].message.content.strip()
                    idx = idx+1
                    end_time = time.time()
                    elapsed = end_time - start_time
                    print(f"[问题 {idx}] 响应长度: {len(answer)}, 耗时: {elapsed:.2f}秒")
                    # 更新上下文字符串
                    context_str += f"User: {user.strip()}\nAssistant: {answer}\n"
                    results.append((user.strip(), answer))
                except Exception as e:
                    print(f"处理第 {line_number} 行时出错：{e}")
                    results.append((user.strip(), f"错误: {str(e)}"))

    except FileNotFoundError:
        print(f"错误：文件 {file_path} 不存在")
    except Exception as e:
        print(f"读取文件时出错：{e}")

    return results

# 初始化 OpenAI 客户端
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"  # 根据服务配置调整
)

# 调用函数
file_path = "test1.txt"
answers = ask_questions(file_path, client)

# 打印结果
for question, answer in answers:
    print(f"问题：{question}\n回答：{answer}\n")

